/**
 * 新开页面的业务js
 */


$(document).ready(function()
{
	/*设置工作台*/
	 $(".console-label").css({width:"0px"});
	 $(".console-items-container").css({left:"0px"});
	 changyongxiangmu("changyongxiangmu");// 右侧页签常用项目初始化
	 deptList_jiezhen();//加载科室
	loadAllSelectVal();// 加载所有下拉列表数据----数据库加载
	xkSelectDiv();
	/*页面上select2 控件初始化*/
	$("select").select2({
		language: "zh-CN"
	});
	
	// addMoreType();
	// addYizhudan();

	// 侧栏控制区域hover事件
	var rightTabFlag = true;
	$(".right-container-content").hover(function()
	{
		$(".slide-control").find(".slide-control-btn").fadeIn(0);
	}, function()
	{
		$(".slide-control").find(".slide-control-btn").fadeOut(0);
	});
	// 侧栏区域hover事件
	$(".slide-control").hover(function()
	{
		$(".slide-control").find(".slide-control-btn").fadeIn(0);
	}, function()
	{
		$(".slide-control").find(".slide-control-btn").fadeOut(0);
	});
	// 控制按钮点击事件
	$(".slide-control").click(function()
	{
		if (rightTabFlag)
		{
			$('#controlRightTabDiv').animate(
			{
				'width' : "99%"
			}, "fast");
			$(".right-container").addClass('hidden');
			rightTabFlag = false;
		}
		else
		{
			$('#controlRightTabDiv').animate(
			{
				'width' : "80%"
			}, "fast");
			$(".right-container").removeClass('hidden');
			rightTabFlag = true;
		}
	});
	coverEvent();//遮盖层点击事件，隐藏医嘱列表，及清空input
	

});

//新开加载诊断信息
function addNeworderZhenduan(vaa01){
	var arr = [];
	var params = {};
	params.vac01 = vac01;
	$.ajax({
		data:params,
		url : rootUrl + "/treatment/getZhenduanShouye",
		type:'get',
		dataType:'json',
		success:function(data){
			var list = data.list;
			var str;
			if(list && list.length>0){
				var temp = list[0];
				var vaf01 =temp.vaf01;
				for(var i = 0;i<list.length;i++){
					if(vaf01 == list[i]['vaf01']){
						arr.push(list[i]);
					}
				}
				for(var j=0;j<arr.length;j++){
					if(arr[j].cam01!="0"&&arr[j].cam01){
						str = '{"cam01":"'+arr[j]['cam01']+'"}';
					}
					else if(arr[j].bak01a!="0"&&arr[j].bak01a)
					{
						str = '{"bak01a":"'+list[j].bak01a+'"}';
					}
					$("#lczds_select").tagsinput('add',list[j]['vao15'],str);//name id 替换为数据里的就好了
				}
			}
		}
	
	})
}

// 表格时间填充
function setTime(lastTimeInput)
{
	var date = new Date();
	$(lastTimeInput).val(date.Format("yyyy-MM-dd hh:mm:ss"));
}

//遮盖层点击事件
function  coverEvent(){
	$("#cover").on("click",function(){
	  $(".changeTdDiv").hide();
  	  $("#cover").addClass("hidden");
//  	  $("#" + activeAdviceInputId).val("");
	})
}

function init()
{
		// 检验
		JianyanTable();
		// 加载西药第一行
		westMedicineTable();
		// 中药
		chinaMedicineTable();
		// 检查
		JianchaTable();
		// 手术
		shoushuTable();
		// 治疗
		zhiliaoTable();

}

/**
 * 新增同类医嘱单
 */
function newTab()
{
	
	// add <li>
	var li = $("<li><a href='#Xiyao' data-toggle='tab' onclick='typeClick(\"Xiyao\")'>西成药处方</a></li>");
	$("#new_order_list").append(li);
	// add <div>

	// 初始化第一行
	if (topTab == "Xiyao")
	{
		westMedicineTable();
	}
	else if (topTab == "Zhongyao")
	{
		chinaMedicineTable();
	}
	else if (topTab == "Jianyan")
	{
		JianyanTable();
	}
	else if (topTab == "Jiancha")
	{
		JianchaTable();
	}
	else if (topTab == "Shoushu")
	{
		shoushuTable();
	}
	else if (topTab == "Zhiliao")
	{
		zhiliaoTable();
	}
}

// 注册全局键盘事件
document.onkeydown=function(event){
    var e = event || window.event || arguments.callee.caller.arguments[0];
    if(e && e.keyCode==27){ // 按 Esc
  	  $(".changeTdDiv").hide();
  	  $("#cover").addClass("hidden");
//  	$("#" + activeAdviceInputId).val("");
      }
    else if(e && e.keyCode === 40){ // 按向下箭头
  	  if(($(".changeTdDiv").attr("style"))&&($(".selectDiv").attr("style"))&&($(".changeTdDiv").attr("style").indexOf("block")<0)&&($(".selectDiv").attr("style").indexOf("block")<0)){
  		  if($(".select2-container--open").length<1)
  		  {
  			  adviceInputFocus();
  		  }
  	  }else  if(($(".changeTdDiv").attr("style"))&&($(".changeTdDiv").attr("style").indexOf("block")>0)){
  		  $(".changeTdDiv").find("table tbody").find(".choseedTr").next().addClass("choseedTr").siblings().removeClass("choseedTr");
  	  }else if(($(".selectDiv").attr("style"))&&($(".selectDiv").attr("style").indexOf("block")>0)){
  		  $(".selectDiv").find("table tbody").find(".choseedTr").next().addClass("choseedTr").siblings().removeClass("choseedTr");
  	  }
    }else if(e && e.keyCode === 38){ //向上箭头
  	  if(($(".changeTdDiv").attr("style"))&&($(".changeTdDiv").attr("style").indexOf("block")>0)){
  		  $(".changeTdDiv").find("table tbody").find(".choseedTr").prev().addClass("choseedTr").siblings().removeClass("choseedTr");
  	  }else if(($(".selectDiv").attr("style"))&&($(".selectDiv").attr("style").indexOf("block")>0)){
  		  $(".selectDiv").find("table tbody").find(".choseedTr").prev().addClass("choseedTr").siblings().removeClass("choseedTr");
  	  }
    }else if(e && e.keyCode === 13){ //回车事件
  	  if(($(".changeTdDiv").attr("style"))&&($(".changeTdDiv").attr("style").indexOf("block")>0)){
  		 var id =  $(".changeTdDiv").find("table tbody").find(".choseedTr").attr("id");
  		 if(id){
  			 if((topTab=="Xiyao")||(topTab=="Zhongyao")){
  				 addBbxInfoYaopin(id);
  			 }else{
  				 addBbxInfoFeiyaopin(id);
  			 }
  		 }
  	  }else if(($(".selectDiv").attr("style"))&&($(".selectDiv").attr("style").indexOf("block")>0)){
//  		  var id= $(".selectDiv").find("table tbody").find(".choseedTr").attr("data-id");
//  		  var name = $(".selectDiv").find("table tbody").find(".choseedTr").find("td:eq(1)").text();
//  		  $(".selectDiv").find("table tbody").find(".choseedTr").trigger("dblclick");;
  	  }
    }
};

function adviceInputFocus()
{
	debugger;
	if (topTab == "Xiyao")
	{
		var lastInput = $("#west_medicine_table").find(".xiyao_yznr");
		$(lastInput).last().focus();
	}
	else if (topTab == "Zhongyao")
	{
		var chLastInput = $("#china_medicine_table").find(".zhongyao_yznr");// 定义增加行的相对位置
		$(chLastInput).last().focus();
	}
	else if (topTab == "Jiancha")
	{
		var cxLastInput = $("#xk_jc_table").find(".jiancha_yznr");// 定义增加行的相对位置
		$(cxLastInput).last().focus();
	}
	else if (topTab == "Jianyan")
	{
		var cyLastInput = $("#xk_jy_table").find(".jianyan_yznr");// 定义增加行的相对位置
		$(cyLastInput).last().focus();
	}
	else if (topTab == "Shoushu")
	{
		var ssLastInput = $("#xk_shoushu_table").find(".shoushu_yznr");// 定义增加行的相对位置
		$(ssLastInput).last().focus();
	}
	else if (topTab == "Zhiliao")
	{
		var zlLastInput = $("#xk_zhiliao_table").find(".zhiliao_yznr");// 定义增加行的相对位置
		$(zlLastInput).last().focus();
	}
}

// 点击新开同类医嘱单增加同类tab

function addYizhudan()
{
	$("#new_similar").on("click", function()
	{
		var newHtml = $("#new_order_list li.active").clone();
		var lastLi = $("#new_order_list li").children("a").last().parents("li");
		lastLi.after(newHtml);
	})
}

// 加载常用项目
function changyongxiangmu(id)
{
	rightTab = id;
	var that = this;
	$.ajax(
	{
	url : rootUrl + "/doctoradviceeditor/personalOftenList" + topTab,
	type : "post",
	async : true,
	data :
	{
	"lBCE01" : bce01,
	"lBCK01" : bck01,
	"aACF01" : acf01,
	"bdp02" : '自费'
	},
	dataType : 'json',
	success : function(data)
	{
		that.laytplUrl(myurl + "/module/changyongxiangmu.html", data, function(data, html)
		{
			$("#changyongContent").empty().append(html);
			addCyxmEvent();
		});
	}
	});
}
function addCyxmEvent()
{
	$("#changyongxiangmu_table tr").dblclick(function()
	{
		var dataStr = $(this).attr("data-info");
		var id = $(this).attr("id");
		var dataObj = JSON.parse(dataStr);
		obj = $.extend(dataObj,
		{
			'id' : id
		});
		queryAdviceInfo(obj);
	})
}

// 常用治疗方案
function zhiliaofangan(id)
{
	rightTab = id;
	var that = this;
	$.ajax(
	{
	url : rootUrl + "/doctoradviceeditor/personaltherapeuticregimen",
	type : "post",
	data :
	{
	"lACF01" : acf01,
	"lBCE01" : bce01,
	"lBCK01" : bck01,
	"currPage" : 1,
	"pageSize" : 15
	},
	dataType : 'json',
	success : function(data)
	{
		that.laytplUrl(myurl + "/module/changyongzhiliao.html", data, function(data, html)
		{
			$("#changyongContent").html(html);
			$(".changeTdDivT").slideDown();
			// 加载全部治疗方案
			$.ajax(
			{
			url : rootUrl + "/doctoradviceeditor/treelist",
			type : "get",
			data :
			{
			"lBEH01" : '9',
			"BCE01" : bce01,
			"BCK01" : bck01
			},
			dataType : 'json',
			success : function(data)
			{
				var list = data.list;
				$('#treeT').treeview(
				{
					data : list
				});
				// $("#tree-tableT").empty();
				$('#treeT').on('nodeSelected', function(event, data)
				{
					// 查询其它项目信息
					otherListT(data["bdo01"]);
				});
				//							
			}
			});
		});
	}
	});
}

// 常用诊断方案
function zhenduan(id)
{
	rightTab = id;
	var that = this;
	$.ajax(
	{
	url : rootUrl + "/treatment/persontreamentlist",
	type : "get",
	data :
	{
	"bce01" : bce01,
	"currPage" : 1,
	"pageSize" : 20
	},
	dataType : 'json',
	success : function(data)
	{
		that.laytplUrl(myurl + "/module/changyongzhenduan.html", data, function(data, html)
		{
			$("#changyongContent").html(html);
		});
	}
	});
}
// 中药参考
function zhongyaocankao(id)
{
	rightTab = id;
	var that = this;
	that.laytplUrl(myurl + "/module/zhongyao_cankao.html",
	{}, function(data, html)
	{
		$("#changyongContent").html(html);
		// 加载中药参考树
		$.ajax(
		{
		url : rootUrl + "/doctoradviceeditor/treelist",
		type : "get",
		data :
		{
		"lBEH01" : '3',
		"BCE01" : bce01,
		"BCK01" : bck01
		},
		dataType : 'json',
		success : function(data)
		{
			var list = data.list;
			$('#zyck_tree').treeview(
			{
				data : list
			});
			$('#zyck_tree').on('nodeSelected', function(event, data)
			{
				// 加载点击数节点数据
				zhongyaocank_tree_list("1", data["bdo01"], curr);
			});
		}
		});
	});
}
// 树节点数据
function zhongyaocank_tree_list(lBDA01, lBDO01, curr)
{
	var bad01 = "('3')";
	$.ajax(
	{
	url : rootUrl + "/doctoradviceeditor/medtreetodetail",
	type : "get",
	data :
	{
	"lBDO01" : lBDO01,
	"lBDA01" : lBDA01,
	"lACF01" : 1,
	"lSql" : '%',
	"lBBX09" : 1,
	"BCKyf" : 0,
	"vaf58" : 0,
	"bda01" : bad01,
	"lBEH01" : 1,
	"lBCE01" : bce01,
	"lBCK01" : bck01,
	"abc02" : "医保",
	"bdp02" : "医保",
	"BCKyf" : 0,
	currPage : curr,
	pageSize : pageSize
	},
	dataType : 'json',
	success : function(data)
	{
		var list = data.list;
		var $xiangxixiangmu = $("#zyck_tree_table");
		// append性能低，改为laytpl模板加载
		laytplUrl(myurl + "/module/tree-table-zhongyaocankao.html", data, function(data, html)
		{
			$xiangxixiangmu.empty().append(html);
			var pages = parseInt(data.total) % parseInt(pageSize);
			if (pages == 0)
			{
				totalPage = parseInt(data.total) / parseInt(pageSize);
			}
			else
			{
				totalPage = parseInt(data.total - pages) / parseInt(pageSize) + 1
			}
			laypage(
			{
			cont : 'zyck_page',
			pages : totalPage,
			// skip: true, //是否开启跳页
			// skin: '#33b818',
			groups : 3, // 连续显示分页数
			curr : curr || 1,
			jump : function(obj, first)
			{
				if (!first)
				{
					zhongyaocank_tree_list(lBDA01, lBDO01, obj.curr);
				}
			}
			});
		});
	}
	});

}
/* 诊断下拉框 */
function xkSelectDiv()
{
	$(".bootstrap-tagsinput").on("click", function()
	{
		 var e=arguments.callee.caller.arguments[0]||event; 
		 if (e && e.stopPropagation) { 
		  // this code is for Mozilla and Opera
		  e.stopPropagation(); 
		 } else if (window.event) { 
		  // this code is for IE 
		  window.event.cancelBubble = true; 
		 } 
		var thisLeft = $(this).offset().left;
		var thisTop = $(this).offset().top - 110;
		var thisheight = $(this).outerHeight() + 1;
		$("#neworder_zhenduan").slideDown();
		$("#neworder_zhenduan").css(
		{
		position : "absolute",
		left : thisLeft,
		top : thisTop + thisheight + "px",
		display : "block"
		})
		$("#refund").css(
		{
			"z-index" : 999
		})
		addChangyongzhenduan();
		keySearchJibingEvent();//疾病搜索
		// hideDiv(".selectDiv");
	})
}
function keySearchJibingEvent(){ //诊断疾病回车搜索
	$("#search_jibing").keydown(function (e) {
		if (e.which === 13) {
			searchJibingEvent();
		}
	});
	
}
// 诊断数据加载
function addChangyongzhenduan()
{
	// 加载疾病
	var url = rootUrl + "/treatment/jibingList";
	var params =
	{};
	$.ajax(
	{
	url : url,
	data : params,
	dataType : 'json',
	type : 'get',
	async : true,
	success : function(data)
	{
		var list = data.list;
		$('#jibing-tree').treeview(
		{
			data : list
		});
		$('#jibing-tree').on('nodeSelected', function(event, data)
		{
			$("#search_jibing").val('');
			// 查询疾病详细项目列表
			xiangxiList(data['id']);
		});
	}
	});
	var data = bingrenVaoList;
	if (data.length > 0)
	{
		laytplUrl(myurl + "/module/zhenduan_table.html", data, function(data, html)
		{
			$("#xydqzd").empty().append(html);
		});
	}
	else
	{
		// var html="<div class='wulishizhenduan'><span>该病人无历史诊断</span></div>"
		// $("#xydqzd").html(html);
		data =
		{};
		laytplUrl(myurl + "/module/wulishizhenduan_table.html", data, function(data, html)
		{
			$("#xydqzd").html(html);
		});
	}

}
/*
 * function editAdvice_neworder(dataObj){ console.log(dataObj) }
 */
// 诊断疾病-根据cag01查询详细
function xiangxiList(cag01)
{
	var url = rootUrl + "/treatment/jibingInfo";
	var params =
	{};
	params.cag01 = cag01;
	$.get(url, params, function(data)
	{
		if (data)
		{
			laytplUrl(myurl + "/module/tree-table-jibing2.html", data, function(data, html)
			{
				$("#jibing-tree-table").empty().append(html);
				$("#neworder_zhenduan").find("table tbody tr:eq(0)").addClass("choseedTr");
			});
		}
	});
}
//诊断疾病搜索
function searchJibingEvent(){
	layer.msg('查询中....', {icon: 16,skin: 'layui-layer-msg16',shade: [0.1, '#393D49'],time:1*500});  
	var text = $("#search_jibing").val();
	$.ajax({
		url : rootUrl + "/clidoctor/queryJibingByText",
		type : "get",
		dataType : 'json',
		data:{"txt":"%"+text+"%"},
		success : function(data) {
			if(data.list.length>0){
				laytplUrl(myurl+"/module/tree-table-jibing-search.html",data,function(data,html){
					$("#jibing-tree-table").empty().append(html);
					$("#neworder_zhenduan").find("table tbody tr:eq(0)").addClass("choseedTr");
				});
			}else{
				$("#jibing-tree-table").empty();
			}
		}
	});
}
// 诊断标签添加
function zdSelectResult2(zdid, zdname)
{
	$("#lczds_select").tagsinput('add', zdname, zdid);
	$("#neworder_zhenduan").hide();

}
// 编辑诊断添加
function editZhenDuanEvent(cbm01)
{
	var lVAA01 = vaa01;
	var lVAE01 = vac01;
	var lVAF01 = cbm01;
	var lVAF01A = cbm01;
	var acf01 = 1;
	$.ajax(
	{
	url : rootUrl + "/doctoradviceeditor/storagenewdiagnosisrecord",
	type : "post",
	dataType : 'json',
	data :
	{
	"lVAA01" : lVAA01,
	"lVAE01" : lVAE01,
	"lVAF01" : lVAF01,
	"lVAF01A" : lVAF01A,
	"acf01" : acf01
	},
	success : function(data)
	{
		if (data)
		{
			var list = data.list;
			var str;
			for(var i=0;i<list.length;i++){
				if(list[i].cam01!="0"&&list[i].cam01){
					str = '{"cam01":"'+list[i]['cam01']+'"}';
				}
				else if(list[i].bak01a!="0"&&list[i].bak01a)
				{
					str = '{"bak01a":"'+list[i].bak01a+'"}';
				}
				$("#lczds_select").tagsinput('add',list[i]['bak05'],str);//name id 替换为数据里的就好了
			}
		}
	}
	});
}
// 右侧常用诊断双击到诊断标签
function xiaDaZhenDuan(vao15, vao01)
{
	$("#lczds_select").tagsinput('add', vao15, vao01);
}

// //点击DIV之外的区域，div消失
document.body.onclick = function (event)
{
	debugger;
	var e = event || window.event;
	var elem = e.srcElement || e.target;
	while (elem)
	{
		if (elem.className == "bootstrap-tagsinput" || elem.className == "selectDiv" || elem.className == "list-group-item node-jibing-tree" ||
				elem.className == "list-group-item node-bangliruyuan-tree" || elem.id == "tree-table" || elem.className == "laypage_main laypageskin_default" ||
				elem.className == "changeTdDiv" || elem.className == "div_show" || elem.className == "list-group-item node-tree node-selected"||
				elem.className=="list-group-item node-zhenduan-tree"||$(elem).parents(".select-container").attr("id") == "banliruyuan_zhenduan"||
	        	$(elem).parents(".select-container").attr("id") == "shouye_zhenduan"||elem.className=="list-group-item node-bangliruyuan-tree node-selected"||
	        	elem.className=="list-group-item node-zhenduan-tree node-selected"||$(elem).parents(".select-container").attr("id") == "neworder_zhenduan"
	        		||elem.className=="list-group-item node-jibing-tree node-selected")
		{
			return;
		}
		elem = elem.parentNode;
	}
	$(".selectDiv").hide();
	$(".changeTdDiv").hide();
	$("#cover").addClass("hidden");
//	 $("#" + activeAdviceInputId).val("");

}
function closeChangeTdDiv(){
	 $(".changeTdDiv").hide();
	 $("#cover").addClass("hidden");
//	 $("#" + activeAdviceInputId).val("");
}
// input输入事件事件
function inputEvent(id)
{
	var currentInput = $("#" + id).focus();
	/* 按回车按钮后弹出下拉框 */
	currentInput.keydown(function(e)
	{
		var inputText = $(this).val();
		if (e.which === 13)
		{
			var that = this;
			$("#cover").removeClass("hidden");
			getDropList(id, inputText);
		}
	});

	$("#" + id).on("dblclick", function()
	{// 点击出现下拉
		$("#cover").removeClass("hidden");
		var inputText = $(this).val();
		getDropList(id, inputText);
	})
}

/* 点击出现下拉框 */
function getDropList(inputId, inputText)
{
	$("#tree-table").empty();
	$("#tree_page").empty();
	$("#search_page").hide();
	activeAdviceInputId = inputId;// 更新激活当前激活的input框ID
	var flagTop = $("#" + inputId).parent().position().top;
	if (flagTop > 0)
	{
		// css
		var thiswidth = $("#" + inputId).parent().outerWidth();
		var thisLeft = $("#" + inputId).parent().offset().left;
		var thisTop = 188;
		// var thisheight=$("#"+inputId).parent().outerHeight()+1;
		$(".changeTdDiv").slideDown();
		$(".changeTdDiv").css(
		{
		// position:"absolute",
		left : thisLeft + thiswidth,
		top : thisTop + "px",
		display : "block"
		})
		$("#refund").css(
		{
			"z-index" : 999
		})

	}
	else
	{

		// css
		var thisLeft = $("#" + inputId).parent().offset().left;
		var thisTop = $("#" + inputId).parent().offset().top;
		var thisheight = $("#" + inputId).parent().outerHeight() + 1;
		$(".changeTdDiv").slideDown();
		$(".changeTdDiv").css(
		{
		// position:"absolute",
		left : thisLeft,
		top : thisTop + thisheight + "px",
		display : "block"
		})
		$("#refund").css(
		{
			"z-index" : 999
		})
	}
	$("#search_medicine").focus();
	$("#search_medicine").val(inputText);// 搜索框赋值
	huicheSearch(); // 搜索框回车事件
	adviceSousuo(inputText);
	// hideDiv(".changeTdDiv");

	// load tree
	// 构造树形结构json
	var lbeh01 = configBeh01();
	// var lbeh01 = initGloableParams();
	$.ajax(
	{
	url : rootUrl + "/doctoradviceeditor/treelist",
	type : "get",
	data :
	{
	"lBEH01" : lbeh01,
	"BCE01" : bce01,
	"BCK01" : bck01
	},
	dataType : 'json',
	success : function(data)
	{
		var list = data.list;
		$('#tree').treeview(
		{
			data : list
		});
		selectBotstrapTree(inputId);
	}
	});

	// })
}

function huicheSearch()
{
	$("#search_medicine").keydown(function(e)
	{
		if (e.which === 13)
		{
			changeBbx1();
		}
	});
	$("#changeBbx1").on("click", function()
	{
		changeBbx1();
	})
}

// 树节点选中事件
function selectBotstrapTree(inputId)
{
	$('#tree').off('nodeSelected').on('nodeSelected', function(event, data)
	{
//		$("#" + activeAdviceInputId).val('');
		$("#search_medicine").val('');
		// 查询详细项目列表
		if(topTab=="Xiyao")
		  {
			  // 查询西药品信息
			  yaopinList("1",data["bdo01"],inputId,curr,data["bdm01"]);
		  }
		  else if(topTab=="Zhongyao")
		  {
			  // 查询中药品信息
			  yaopinList("3",data["bdo01"],inputId,curr,data["bdm01"]);
		  }
		else
		{
			// 查询其它项目信息
			otherList(data["bdo01"], inputId);
		}
	});
}
/**
 * 根据首字母检索对应类型医嘱
 */
function adviceSousuo(sqltext)
{
	offset = 0;
	adviceSousuo_public(sqltext)
}

/**
 * 搜索医嘱调用
 * 
 * @param sqltext
 */
function adviceSousuo_public(sqltext)
{
	$("#getBack").attr("disabled", true);
	$("#getNext").attr("disabled", true);
	if (sqltext != '')
	{
		var beh01;
		switch (topTab)
		{
			case "Xiyao" :
				beh01 = "1";
				break;
			case "Zhongyao" :
				beh01 = "3";
				break;
			case "Jianyan" :
				beh01 = "5";
				break;
			case "Jiancha" :
				beh01 = "4";
				break;
			case "Shoushu" :
				beh01 = "6";
				break;
			case "Zhiliao" :
				beh01 = "7";
				break;
			case "Weicai" :
				beh01 = "8";
				break;
		}
		var url = rootUrl + "/clischemedefine/adviceSousuo";
		var params =
		{};
		params.sqltext = '%' + sqltext + '%';
		params.acf01 = 1;
		params.bbx09 = 1;
		params.beh01 = beh01;
		params.bck01 = bck01;
		params.bce01 = bce01;
		params.bckyf = 0;
		params.abc02 = '普通';
		params.bdp02 = '自费';
		params.vaf58 = 0;
		params.offset = offset;
		$.get(url, params, function(data)
		{
			var $xiangxixiangmu = $("#tree-table");
			$("#tree_page").hide();
			$("#search_page").show();
			// append性能低，改为laytpl模板加载
			if ((topTab == "Xiyao") || (topTab == "Zhongyao"))
			{
				laytplUrl(myurl + "/module/tree-table-yaopin.html", data, function(data, html)
				{
					$xiangxixiangmu.empty().append(html);
					$(".changeTdDiv").find("table tbody tr:eq(0)").addClass("choseedTr");
				});
			}
			else
			{
				laytplUrl(myurl + "/module/tree-table-feiyaopin.html", data, function(data, html)
				{
					$xiangxixiangmu.empty().append(html);
					$(".changeTdDiv").find("table tbody tr:eq(0)").addClass("choseedTr");
				});
			}
			$("#getBack").attr("disabled", false);
			$("#getNext").attr("disabled", false);
			// 按钮状态处理
			// 禁止上一步按钮
			if (offset == 0)
			{
				$("#getBack").attr("disabled", true);
				$("#getNext").attr("disabled", false);
				if (!data || data.list.length < 10)
				{
					$("#getBack").attr("disabled", true);
					$("#getNext").attr("disabled", true);
				}
			}
			else
			{
				$("#getBack").attr("disabled", false);
				$("#getNext").attr("disabled", false);
				if (!data || data.list.length < 10)
				{
					$("#getBack").attr("disabled", false);
					$("#getNext").attr("disabled", true);
				}
			}

		});
	}
}

// 医嘱搜索不分页，每次显示10条数据
function adviceSearchEvent(type)
{ //
	var sousuoText = $("#search_medicine").val();
	if (type == 0)
	{
		offset = 0;
		adviceSousuo_public(sousuoText);
	}
	else if (type == -1)
	{
		offset -= 10;
		adviceSousuo_public(sousuoText);
	}
	else if (type == 1)
	{
		offset += 10;
		adviceSousuo_public(sousuoText);
	}
}
function configBeh01()
{
	var lbeh01 = "5";
	if (topTab == "Xiyao")
	{
		lbeh01 = "1";
	}
	else if (topTab == "Zhongyao")
	{
		lbeh01 = "3";
	}
	else if (topTab == "Jiancha")
	{
		lbeh01 = "4";
	}
	else if (topTab == "Jianyan")
	{
		lbeh01 = "5";
	}
	else if (topTab == "Shoushu")
	{
		lbeh01 = "6";
	}
	else if (topTab == "Zhiliao")
	{
		lbeh01 = "7";
	}
	else if (topTab == "Weicai")
	{
		lbeh01 = "8";
	}
	return lbeh01;
}

// 加载tree-table内容(药品)
function yaopinList(lBDA01, lBDO01, inputId, curr,bdm01)
{
	var bda01 = "";
	switch (topTab)
	{
		case "Xiyao" :
			bda01 = "('1','2')";
			break;
		case "Zhongyao" :
			bda01 = "('3')";
			break;
	}
	$.ajax(
	{
	url : rootUrl + "/doctoradviceeditor/medtreetodetail",
	type : "get",
	data :
	{
	"lBDO01" : lBDO01,
	"lBDA01" : lBDA01,
	"lACF01" : 1,
	"lSql" : '%',
	"lBBX09" : 1,
	"BCKyf" : 0,
	"vaf58" : 0,
	"bda01" : bda01,
	"lBEH01" : '3',
	"lBCE01" : bce01,
	"lBCK01" : bck01,
	"abc02" : $("#abc02").text(),
	"bdm01":bdm01,
	"bdp02" : $("#patient_bdp02").text(),
	"BCKyf" : 0,
	currPage : curr,
	pageSize : pageSize
	},
	dataType : 'json',
	success : function(data)
	{
		var list = data.list;
		data.bdm01 = bdm01;
		$("#tree_page").show();
		$("#tree_page").empty();
		$("#search_page").hide();
		var $xiangxixiangmu = $("#tree-table");
		// append性能低，改为laytpl模板加载
		laytplUrl(myurl + "/module/tree-table-yaopin.html", data, function(data, html)
		{
			$xiangxixiangmu.empty().append(html);
			$(".changeTdDiv").find("table tbody tr:eq(0)").addClass("choseedTr");
			var pages = parseInt(data.total) % parseInt(pageSize);
			if (pages == 0)
			{
				totalPage = parseInt(data.total) / parseInt(pageSize);
			}
			else
			{
				totalPage = parseInt(data.total - pages) / parseInt(pageSize) + 1
			}
			laypage(
			{
			cont : 'tree_page',
			pages : totalPage,
			// skip: true, //是否开启跳页
			// skin: '#33b818',
			groups : 5, // 连续显示分页数
			curr : curr || 1,
			jump : function(obj, first)
			{
				if (!first)
				{
					yaopinList(lBDA01, lBDO01, inputId, obj.curr,bdm01);
				}
			}
			});
		});
	}
	});
}
// 加载tree-table内容（非药品）
function otherList(lBDO01, inputId, curr)
{
	var bad01;
	var beh01;
	switch (topTab)
	{
		case "Jianyan" :
			bad01 = "L";
			beh01 = "5";
			break;
		case "Jiancha" :
			bad01 = "E";
			beh01 = "4";
			break;
		case "Shoushu" :
			bad01 = "S";
			beh01 = "6";
			break;
		case "Zhiliao" :
			bad01 = "T";
			beh01 = "7";
			break;
		case "Weicai" :
			bad01 = "4";
			beh01 = "8";
			break;
	}
	$.ajax(
	{
	url : rootUrl + "/doctoradviceeditor/classificationretrieval",
	type : "post",
	data :
	{
	"lBDO01" : lBDO01,
	"lACF01" : 1,
	"lSql" : '%',
	"lBBX09" : 1,
	"lBEH01" : beh01,
	"lBCE01" : bce01,
	"lBCK01" : bck01,
	"abc02" : "普通",
	"bdp02" : "自费",
	"productId" : 9999,
	"programId" : 9999,
	"paramNo" : 60,
	"lbda01" : bad01,
	currPage : curr,
	pageSize : pageSize
	},
	dataType : 'json',
	success : function(data)
	{
		var list = data.list;
		$("#tree_page").show();
		$("#tree_page").empty();
		$("#search_page").hide();
		var $xiangxixiangmu = $("#tree-table");
		laytplUrl(myurl + "/module/tree-table-feiyaopin.html", data, function(data, html)
		{
			$xiangxixiangmu.empty().append(html);
			$(".changeTdDiv").find("table tbody tr:eq(0)").addClass("choseedTr");
			var pages = parseInt(data.total) % parseInt(pageSize);
			if (pages == 0)
			{
				totalPage = parseInt(data.total) / parseInt(pageSize);
			}
			else
			{
				totalPage = parseInt(data.total - pages) / parseInt(pageSize) + 1
			}
			laypage(
			{
			cont : 'tree_page',
			pages : totalPage,
			// skip: true, //是否开启跳页
			// skin: '#33b818',
			groups : 5, // 连续显示分页数
			curr : curr || 1,
			jump : function(obj, first)
			{
				if (!first)
				{
					otherList(lBDO01, inputId, obj.curr);
				}
			}
			});
		});
	}
	});

}
function otherListT(lBDO01)
{
	var bad01;
	var beh01;
	$.ajax(
	{
	url : rootUrl + "/doctoradviceeditor/classificationretrieval",
	type : "post",
	data :
	{
	"lBDO01" : lBDO01,
	"lACF01" : 1,
	"lSql" : '%',
	"lBBX09" : 1,
	"lBEH01" : "9",
	"lBCE01" : bce01,
	"lBCK01" : bck01,
	"abc02" : "普通",
	"bdp02" : "自费",
	"productId" : 9999,
	"programId" : 9999,
	"paramNo" : 60,
	"lbda01" : "9",
	"currPage" : 1,
	"pageSize" : 15
	},
	dataType : 'json',
	success : function(data)
	{
		var list = data.list;
		var $xiangxixiangmu = $("#tree-tableT");
		// append性能低，改为laytpl模板加载
		laytplUrl(myurl + "/module/tree-table-zhiliaofangan.html", data, function(data, html)
		{
			$xiangxixiangmu.empty().append(html);
		});
	}
	});

}

// 界面所有select框值加载
function loadAllSelectVal()
{
	// 执行性质
	var url1 = rootUrl + "/doctoradvice/doctoradviceexecuteproperty";
	var params1 = {};
	params1.asign = 0;
// 中药煎法
	var url2 = rootUrl + "/clischemedefine/findspecialtreament";
	var params2 = {};
	params2.lBDA01 = 'T';
	params2.lBBX13 = '3';
// 检验样本
	var url3 = rootUrl + "/doctoradviceeditor/yangben";
	var params3 = {};
var url4 = rootUrl + "/clinewadvice/getOperationpro"; // 手术附加项目
var url5 = rootUrl + "/clinewadvice/getAnaesthesiaItem"; // 手术麻醉项目
// 用药目的
	var url6 = rootUrl + "/clinewadvice/getYongyaomudiList";
// 手术人员列表
	var url7 = rootUrl + "/clinewadvice/shoushurenyuanList";
// 病人常用诊断
	var url8 = rootUrl + "/treatment/querypatienttreatmentrecord";
	var params8 = {};
	params8.vaa01 = vaa01;
	params8.acf01 = 1;
	params8.vaa07 = vac01;
	params8.currPage = 1;
	params8.pageSize = 10;
var url9 = rootUrl + "/basicinformationquery/zhixingkeshi1";
var url14 = rootUrl+"/clidoctor/aab1";
var url13 = rootUrl+"/clidoctor/queryBce1Info";
var params13 = {};
params13.bck01 = bck01;
// 给药执行
var url21 = rootUrl + "/treatment/geiyaokeshiList";
// 其它医嘱频次
	var url20 = rootUrl + "/treatment/otherPinci";
	$.when(
	// 西药给药途径 -16776
	$.ajax(
			{
			url : rootUrl + "/clinewadvice/geiYaoTuJingList",
			type : "get",
			data :
			{
				"lBBX13" : "2"
			},
			dataType : 'json',
			success : function(data)
			{
				var geiyaotujingList = data.list;
				geiyaoHtml = "<select class='geiyaoHtml' onchange='getGeiyaoZhixing()'>";
				for (var j = 0; j < geiyaotujingList.length; j++)
				{
					console.table(geiyaotujingList);
					geiyaoHtml = geiyaoHtml + "<option id='" + geiyaotujingList[j]["bbx01"] + "' name='" + geiyaotujingList[j]["bbx01"] + "' data-info='"+JSON.stringify(geiyaotujingList[j])+"'>";
					geiyaoHtml = geiyaoHtml + geiyaotujingList[j]["bbx05"];
					geiyaoHtml = geiyaoHtml + "</option>";
				}
				geiyaoHtml += "</select>";
			}
			}),
	// 西药诊疗频次
	$.ajax(
			{
			url : rootUrl + "/clinewadvice/zhenLiaoPinCiList",
			type : "get",
			data :
			{
				"lbdi10" : 1
			},
			dataType : 'json',
			success : function(data)
			{
				var zhenLiaoPinCiList = data.list;
				zhenLiaoPinCiHtml = "<select class='zhenLiaoPinCiHtml'  onchange='jisuanZongliang(this)'>";
				for (var k = 0; k < zhenLiaoPinCiList.length; k++)
				{
					zhenLiaoPinCiHtml = zhenLiaoPinCiHtml + "<option id='" + zhenLiaoPinCiList[k]["bdi06"] + "' name='" + zhenLiaoPinCiList[k]["bdi01"] + "' value='" + zhenLiaoPinCiList[k]["bdi08"] + "'>";
					zhenLiaoPinCiHtml = zhenLiaoPinCiHtml + zhenLiaoPinCiList[k]["bdi02"];
					zhenLiaoPinCiHtml = zhenLiaoPinCiHtml + "</option>";
				}
				zhenLiaoPinCiHtml += "</select>";
			}
			}),
	
	$.post(url1, params1, function(data)
	{
		var list = data.list;
		zhiXingXingZhiHtml = "<select class='zhiXingXingZhiHtml'>";
		for (var k = 0; k < list.length; k++)
		{
			zhiXingXingZhiHtml += "<option id='" + list[k]["fid"] + "' value='" + list[k]["fid"] + "'>";
			zhiXingXingZhiHtml += list[k]["fname"];
			zhiXingXingZhiHtml += "</option>";
		}
		zhiXingXingZhiHtml += "</select>";
	}),
	// 门诊部门
	$.ajax(
			{
			url : rootUrl + "/patientsearch/finddepartments",
			type : "get",
			dataType : 'json',
			data :
			{
				"bce01" : bce01
			},
			success : function(data)
			{
				departmentList = data.list;
				bck01ListHtml = "<select class='bck01ListHtml'>";
				for (var i = 0; i < departmentList.length; i++)
				{
					if (departmentList[i]["bck01"] == bck01)
					{
						bck01ListHtml += "<option value=\"" + departmentList[i]["bck01"] + "\" selected=selected>" + departmentList[i]["bck03"] + "</option>";
					}
					else
					{
						bck01ListHtml += "<option value=\"" + departmentList[i]["bck01"] + "\">" + departmentList[i]["bck03"] + "</option>";
					}
				}
				bck01ListHtml += "</select>";
			}
			}),
	// 中药频次
	$.ajax(
			{
			url : rootUrl + "/clinewadvice/zhenLiaoPinCiList",
			type : "get",
			data :
			{
				"lbdi10" : 2
			},
			dataType : 'json',
			success : function(data)
			{
				var zhenLiaoPinCiList = data.list;
				zhenLiaoPinCiHtml2 = "<select class='zhenLiaoPinCiHtml2'>";
				for (var k = 0; k < zhenLiaoPinCiList.length; k++)
				{
					zhenLiaoPinCiHtml2 = zhenLiaoPinCiHtml2 + "<option value='" + zhenLiaoPinCiList[k]["bdi06"] + "',name='" + zhenLiaoPinCiList[k]["bdi01"] + "',id='" + zhenLiaoPinCiList[k]["bdi08"] + "'>";
					zhenLiaoPinCiHtml2 = zhenLiaoPinCiHtml2 + zhenLiaoPinCiList[k]["bdi02"];
					zhenLiaoPinCiHtml2 = zhenLiaoPinCiHtml2 + "</option>";
				}
				zhenLiaoPinCiHtml2 += "</select>";
			}
			}),
	// 加载中药脚注
	$.get(rootUrl + "/clinewadvice/zhongyaoJiaozhu",
	{}, function(data)
	{
		var list = data.list;
		zhongyaojiaozhuHtml = "<select class='zhongyaojiaozhuHtml'>";
		zhongyaojiaozhuHtml += "<option value='-1'></option>"
		for (var i = 0; i < list.length; i++)
		{
			zhongyaojiaozhuHtml += "<option value='" + list[i]["acx01"] + "'>";
			zhongyaojiaozhuHtml += list[i]["acx02"];
			zhongyaojiaozhuHtml += "</option>";
		}
		zhongyaojiaozhuHtml += "</select>";
	}),
	
	$.post(url2, params2, function(data)
	{
		var list = data.list;
		zhongyaojianfaHtml = "<select class='zhongyaojianfaHtml'>";
		for (var i = 0; i < list.length; i++)
		{
			zhongyaojianfaHtml += "<option value='" + list[i]["bbx01"] + "'>";
			zhongyaojianfaHtml += list[i]["bbx05"];
			zhongyaojianfaHtml += "</option>";
		}
		zhongyaojianfaHtml += "</select>";
	}),
	// 中药用法
	$.get(rootUrl + "/clinewadvice/zhongyaoyongfa",
	{}, function(data)
	{
		var yfList = data.list;
		zhongyaoyongfaHtml = "<select class='zhongyaoyongfaHtml'>";
		for (var i = 0; i < yfList.length; i++)
		{
			zhongyaoyongfaHtml += "<option value='" + yfList[i]["bbx01"] + "'>";
			zhongyaoyongfaHtml += yfList[i]["bbx05"];
			zhongyaoyongfaHtml += "</option>";
		}
		zhongyaoyongfaHtml += "</select>";
	}),
	
	$.get(url3, params3, function(data)
			{
				// 样本列表
				yangbenList = data.list;
				jyyangbenleixing = "<select class='jyyangbenleixing'>";
				for (var j = 0; j < yangbenList.length; j++)
				{
					jyyangbenleixing += "<option value='" + yangbenList[j]['abb01'] + "' >" + yangbenList[j]['abb02'] + "</option>";
				}
				jyyangbenleixing += "</select>";
			}

			),
	
	$.get(url4, function(resp)
			{
				if (resp.result == 'Success')
				{
					debugger;
					var rList = resp.list;
					if (rList.length)
					{
						fujianshoushuListHtml = "<select class='fujianshoushuListHtml form-control'>";
						for (var i = 0; i < rList.length; i++)
						{
							var id = rList[i].bda01 + '|' + rList[i].bbx01 + '|' + rList[i].bbx04 + "|";
							var txt = rList[i].bbx05 + "|" + (rList[i].bdg02 == undefined ? "" : rList[i].bdg02) + "|" + (rList[i].ach02 == undefined ? "" : rList[i].ach02);
							fujianshoushuListHtml += "<option id='" + id + "'>" + txt + "</option>";
						}
						fujianshoushuListHtml += "</select>";
					}
				}

			}),
	
	$.get(url5, function(resp)
	{
		if (resp.result == 'Success')
		{
			var rList = resp.list;
			if (rList.length)
			{
				mazuiHtml +='<div class="radio"><label onclick = "setSsAdviceboxEvent();"><input type="radio" name="mz" style=" position: relative;"  value="" checked><span>无麻醉</span></label></div>';
				// chekbox 展示
				for(var i=0;i<rList.length;i++){
					var id = (rList[i].bda01==undefined?0:rList[i].bda01)+'|'+rList[i].bbx01;
					mazuiHtml += '<div class="radio"><label onclick = "setSsAdviceboxEvent();">';
					mazuiHtml += '<input type="radio" name="mz" style=" position: relative;"  value='+id+'><span>';
					mazuiHtml += rList[i].bbx05;
					mazuiHtml += '</span></label></div>';
				}
			}
		}
	}),
	
	$.get(url6, function(data)
	{
		var list = data.list;
		yongyaomudiHtml = "<select class='yongyaomudiHtml'>";
		for (var i = 0; i < list.length; i++)
		{
			yongyaomudiHtml += "<option value=" + list[i]["biw01"] + ">" + list[i]["biw02"] + "</option>";
		}
		yongyaomudiHtml += "</select>";

	}),
	
	$.get(url7, function(data)
	{
		var list = data.list;
		shoushurenyuanHtml = "<select class='shoushurenyuanHtml'>";
		shoushurenyuanHtml += '<option value="">--请选择--</option>';
		for (var i = 0; i < list.length; i++)
		{
			shoushurenyuanHtml += "<option value='" + list[i]["bce01"] + "'>" + list[i]["bce03"] + "</option>";
		}
		shoushurenyuanHtml += "</select>";
	}),
	
	$.ajax(
	{
	url : url8,
	data : params8,
	dataType : 'json',
	type : 'post',
	success : function(data)
	{
		bingrenVaoList = data.list;
	}
	}),

	
	$.get(url9,{"bck01":yiyuanId}, function(data)
	{
		var list = data.list;
		zhixingkeshi1Html = "<select class='zhixingkeshi1Html'>";
		// zhixingkeshi1Html+='<option value="">--请选择--</option>';
		for (var i = 0; i < list.length; i++)
		{
			zhixingkeshi1Html += "<option value='" + list[i]["bck01"] + "'>" + list[i]["bck03"] + "</option>";
		}
		zhixingkeshi1Html += "</select>";

	}),
	
	
	$.get(url14,{},function(data){
		var list = data.list;
		qiekoudengjiHtml = "<select class='qiekoudengjiHtml'>";
		qiekoudengjiHtml +='<option value="">--请选择--</option>';
		for(var i = 0;i<list.length;i++)
		{
			qiekoudengjiHtml += "<option value="+list[i].aab02+">"+list[i]['aab02']+"</option>";
		}
		qiekoudengjiHtml += "</select>";
	}),
	
	$.get(url20,
			{}, function(data)
			{
				var list = data.list;
				otherPinciHtml = "<select class='otherPinciHtml'>";
				for (var i = 0; i < list.length; i++)
				{
					otherPinciHtml += "<option id='" + list[i]["bdi06"] + "' value='" + list[i]["bdi01"] + "' name='" + list[i]["bdi08"] + "'>" + list[i]["bdi02"] + "</option>";
				}
				otherPinciHtml += "</select>";
			}),
	$.get(url13,params13,function(data)
	{
		var list = data.list;
		kaizhuyishiHtml = "<select class='kaizhuyishiHtml'>";
		for(var i =0 ;i<list.length;i++)
		{
			if(list[i].bce01==bce01)
			{
				kaizhuyishiHtml += "<option selected=true value="+list[i].bce01+" id='"+list[i].bce02+"'>"+list[i].bce03+"</option>";
			}
			else
			{
				kaizhuyishiHtml += "<option value="+list[i].bce01+" id='"+list[i].bce02+"'>"+list[i].bce03+"</option>";
			}
		}
		kaizhuyishiHtml += "</select>";
	}),
	
	$.get(url21,
			{}, function(data)
			{
				var list = data.list;
				geiyaozhixingListHtml = "<select class='geiyaozhixingListHtml'>";
				for (var i = 0; i < list.length; i++)
				{
					if (list[i]["bck01"] == bck01)
					{
						geiyaozhixingListHtml += "<option value='" + list[i]["bck01"] + "' selected='selected'>" + list[i]["bck03"] + "</option>";
					}
					else
					{
						geiyaozhixingListHtml += "<option value='" + list[i]["bck01"] + "'>" + list[i]["bck03"] + "</option>";
					}
				}
				geiyaozhixingListHtml += "</select>";
			})
	).done(function(){
		init();
	});
}

// 根据项目检索
function changeBbx1()
{
	var searchStr = $("#search_medicine").val();
	adviceSousuo_public(searchStr, 0);
	// setTimeout(function(){
	// var searchStr = $("#search_medicine").val();
	// if(searchStr!="")
	// {
	// $("#tree-table tr").hide().filter(":contains('"+searchStr+"')").show();
	// //根据tree-table的所有text()的值过滤
	// }
	// else
	// {
	// $("#tree-table tr").show();
	// }
	// },200);
}

// 常用项目--门诊按照规格下达医嘱/* ScriptId(744) */
function queryAdviceInfo(obj)
{
	if (topTab == "Xiyao" || topTab == "Zhongyao")
	{
		var url = rootUrl + "/medicine/patientcasehistory";
		var params =
		{};
		params.BBY01 = obj.bby01;
		params.productId = 9999;
		params.programId = 9999;
		params.paramNo = 63;
		$.post(url, params, function(data)
		{
			var list = data.list;

			var dataObj = $.extend(list[0],
			{
				"id" : obj.id
			},
			{
				"type" : "cyxm"
			},
			{
				"price" : obj.bby25
			});
			addCyxmYaopin(dataObj);
		});
	}
	else
	{
		var url = rootUrl + "/treatment/gettreatmentitembyid";
		var params =
		{};
		params.BBX01 = obj.bbx01;
		$.post(url, params, function(data)
		{
			var list = data.list;
			var dataObj = $.extend(list[0],
			{
				"id" : obj.id
			},
			{
				"type" : "cyxm"
			},
			{
				"price" : obj.price
			});
			addCyxmFeiyaopin(dataObj);
		});
	}
}

// 根据常用项目增加医嘱(药品)
function addCyxmYaopin(dataObj)
{
	if (topTab == "Xiyao")
	{
		addXiyaoCyxm(dataObj);
	}
	else if (topTab == "Zhongyao")
	{
		addZhongyaoCyxm(dataObj);
	}
}
// 根据常用项目增加医嘱（非药品）
function addCyxmFeiyaopin(dataObj)
{
	if (topTab == "Jiancha")
	{
		addJianchaCyxm(dataObj);
	}
	else if (topTab == "Jianyan")
	{
		addJianyanCyxm(dataObj);

	}
	else if (topTab == "Shoushu")
	{
		addShoushuCyxm(dataObj);
	}
	else if (topTab == "Zhiliao")
	{

		addZhiliaoCyxm(dataObj);
	}
}

// 双击tree-table-tr的事件处理:药品
function addBbxInfoYaopin(str)
{
	var obj = $("#" + str).attr("data-info");
	var obj = JSON.parse(obj);

	if(obj.amount == 0){
		layer.msg("该药品暂无库存，请选择其他药品",{time:2000,icon:0,skin: 'layui-layer-msg0'});
		return;
	}
	if (topTab == "Xiyao")
	{
		addXiyaoBbxInfo(obj);
	}
	else if (topTab == "Zhongyao")
	{
		var flag = true;
		// 添加前判断药品是否重复添加
		var chLastInput = $("#china_medicine_table").find(".zhongyao_yznr");
		$(chLastInput).each(function(index, ele)
		{ // 判断药品不要重复
			if (($(ele).val() == obj.bef07) || ($(ele).val() == (obj.bbx05 + obj.bby06)))
			{
				layer.msg("该药品已经存在！",
				{
				time : 2000,
				icon : 0,
				skin: 'layui-layer-msg0'
				});
				flag = false;
				return false;
			}
		})
		if (flag)
		{
			var bdm01 = $("#"+str).attr("a-bdm01");
			if(bdm01=="8")
			{
				$.ajax({
					url:rootUrl+"/clidoctor/script817",
					type:"get",
					dataType:"json",
					data:{bbx01a:obj.bbx01},
					success:function(json)
					{
						var list = json.list;
						if(list.length<=0)
						{
							layer.msg("该方剂下暂无有效期内的药品！",{time:3000,icon:0,skin: 'layui-layer-msg0'});
						}
						for(var i = 0;i<list.length;i++)
						{
							var temp = list[i];
							temp.type = "treeTable"
							addZhongyaoCyxm(temp);
						}
					}
				});
			}
			else
			{
				addZhongyaoBbxInfo(obj);
			}
		}
	}
}
// 双击tree-table-tr的事件处理：非药品
function addBbxInfoFeiyaopin(str)
{
	var obj = $("#" + str).attr("data-info");
	var obj = JSON.parse(obj);
	if (topTab == "Jiancha")
	{
		addJianchaBbxInfo(obj);
	}
	else if (topTab == "Jianyan")
	{
		addJianyanBbxInfo(obj);
	}
	else if (topTab == "Shoushu")
	{
		addShoushuBbxInfo(obj);
	}
	else if (topTab == "Zhiliao")
	{
		addZhiliaoBbxInfo(obj);
	}
}

// 点击医嘱页签项目事件
function typeClick(id)
{
	topTab = id;
	// 更新变量type
	if (id == '1')
	{
		switch (valueArr['p_100_105002_386'])
		{
			case '1' :
				topTab = "Xiyao";
				break;
			case '3' :
				topTab = "Zhongyao";
				break;
			case 'E' :
				topTab = "Jiancha";
				break;
			case 'L' :
				topTab = "Jianyan";
				break;
			case 'S' :
				topTab = "Shoushu";
				break;
			case 'T' :
				topTab = "Zhiliao";
				break;
		} 
	}
	if (id == "-1") //病历
	{
		if (!vaa01)
		{
			 var e=arguments.callee.caller.arguments[0]||event; 
			 if (e && e.stopPropagation) { 
			  // this code is for Mozilla and Opera
			  e.stopPropagation(); 
			 } else if (window.event) { 
			  // this code is for IE 
			  window.event.cancelBubble = true; 
			 } 
			layer.msg("请选择接诊病人",
			{
				time : 2000,
				icon : 0,
				skin: 'layui-layer-msg0'
			});
			$('#new_order_list a[href="#Jiezhen"]').tab('show');
		}
		else
		{
			var src = dzbl + "/jsp/record/out_interface_doctor.jsp?jsessionids=" + $
//			var src = "http://192.168.1.162:8080/emrweb/jsp/record/out_interface_doctor.jsp?jsessionids=" + $
					.cookie("jsessionids") + "&patientId=" + vaa01 + "&patientName=" + vaa05 + "&vaa07=" + vac01 + "&deptId=" + bck01+"&firstOrRepeat="+vac06;
			$("#shuxiebingli").attr("src", src);
			$("#btn-save-first").trigger("click");
		}
	}else if(id == "0"){
		
	}
	else
	{
		if (!vaa01)
		{
			 var e=arguments.callee.caller.arguments[0]||event; 
			 if (e && e.stopPropagation) { 
			  // this code is for Mozilla and Opera
			  e.stopPropagation(); 
			 } else if (window.event) { 
			  // this code is for IE 
			  window.event.cancelBubble = true; 
			 } 
			 layer.msg("请选择接诊病人",
						{
							time : 2000,
							icon : 0,
							skin: 'layui-layer-msg0'
						});
			$('#new_order_list a[href="#Jiezhen"]').tab('show');
			return false;
		}
		addNeworderZhenduan(vaa01);
		if (topTab == "Zhongyao")
		{
//			$("#zhongyaocankao").parents("li").removeClass("hidden"); //暂时隐藏
		}
		else
		{
			$("#zhongyaocankao").parents("li").addClass("hidden");
		}
		// 如果页面右边的种类常用项目，需要刷新；如果为治疗方案或诊断列表，不需要刷新
		if (rightTab == "changyongxiangmu")
		{
			changyongxiangmu(rightTab);
		}
		else if (rightTab == "zhenliaofangan")
		{
			zhiliaofangan(rightTab);
		}
		else if (rightTab == "chanyongzhenduan")
		{
			zhenduan(rightTab);
		}
		else if (rightTab == "zhongyaocankao")
		{
			zhongyaocankao(rightTab);
		}
	}

}

// 加载诊疗执行科室
// function queryZxksByBbx01AndBck01(bbx01,tdIndex)
// {
// var url = rootUrl+"/clinewadvice/gettreamentoffice";
// var params = {};
// params.BCK01A = bck01;
// params.BBX01 = bbx01;
// $.post(url,params,function(data)
// {
// if (data.list[0])
// {
// zxksId = data.list[0]["bck01b"];
// zxksMc = data.list[0]["bck03"];
// }
// });
// }

// 根据治疗id查询治疗医嘱方案列表
function zhenliaoAdvice(bbx01)
{
	var that = this;
	var url = rootUrl + "/clischemedefine/fetchtreatment";
	var params =
	{};
	params.lBBX01A = bbx01;// 治疗方案ID
	params.lACF01 = 1;
	params.lCheck = 1;
	params.lBCK01 = bck01;
	params.BCKyf = 0;
	params.bdp02 = '自费';
	params.abc02 = '普通';
	$.post(url, params, function(data)
	{
		var list = data.list;
		// 双击获取
		// zhiliaoChangyhongAdd(list);
		// 查看详情
		that.laytplUrl(myurl + "/module/changyongzhiliao_layer.html", list, function(list, html)
		{
			var index = layer.open(
			{
			type : 1,
			scrollbar : false,
			title : "治疗方案医嘱列表",
			area :
			["60%", "90%"],
			shade : 0.3,
			maxmin : true,
			content : html,
			closeBtn : 1,
			success : function()
			{
				zhiliaoAdviceList = list;
				// getCheckedAdvice();
				//处理同组问题；
				addTrToTbody(list);
				$("#remove_action_zlfa").on("click",function() {
					layer.close(index);
				})
			}
			})

		});
	});
}

function addTrToTbody(dList){
    $("#zhiliaoAdvice_tbody").empty();
    for(var i= 0,len = dList.length;i<len;i++){
        var oTr = $('<tr></tr>');
        oTr.data(dList[i]);
        var vaf11_n;
        if (dList[i].bef05 == '2') {
            vaf11_n = '临嘱'
        } else if (dList[i].bef05 == '1') {
            vaf11_n = '长嘱'
        }
        var oTrHtml = String()+
            '<td class="fa-selectTd"><input type="checkbox" class="checkbox-default" /></td>'+     //选择框
            '<td class="fa-valid-time">'+vaf11_n+'</td>'+                                   //期效
            '<td>'+dList[i].nbef07+'</td>'+                                                 //医嘱内容
            '<td class="fa-total">'+dList[i].bef11+'</td>'+                                 //总量
            '<td class="fa-usage">'+dList[i].fusage+'</td>'+                                                   //用法
            '<td class="fa-doctor-advice"></td>'+                                           //医师嘱托
            '<td class="fa-execute-time">'+dList[i].bef22+'</td>'+                          //执行时间
            '<td class="fa-execute-department">'+dList[i].bck03+'</td>'+                    //执行科室
            '<td class="fa-first-day-num">'+dList[i].bef24+'</td>'+                         //首日次数
            '<td class="fa-execute-property">'+dList[i].nbef20+'</td>'+                     //执行性质
            '<td class="fa-execute-property">'+(dList[i].lsqty?dList[i].lsqty:"")+'</td>';                         //库存情况
        oTr.html(oTrHtml);
        if(dList[i].lsqty <=0.00001){
        	$(oTr).find("td").last().css("background-color","red");
        }
        //判断将要添加的tr和它上面的tr是否是同组的，如果是同组的将它们同组显示
        //得到当前预览区域的所有tr
        var $trs = $("#zhiliaoAdvice_tbody").find('tr');
        //定义要同组td的所有class的数组
        var sameGroupTd_arr = ['fa-selectTd','fa-valid-time','fa-usage','fa-first-day-num'];
        //定义组号
        var groupId;

        var prevIndex = i-1;
        var $prevTr = $trs.eq(prevIndex);
        var prevTr_data = $prevTr.data();
        //判断是否是西药
        var isWestern = false;
        if($prevTr.length>0 && (prevTr_data.bda01=='1' || prevTr_data.bda01=='2')&&(dList[i].bda01=='1'|| dList[i].bda01=='2')){
            isWestern = true;
        }
        if($prevTr.length>0 && isWestern && prevTr_data.bbx01b == dList[i].bbx01b){

            //同组显示
            groupId = $prevTr.attr('groupId');
            //得到同组行的第一行，改变它的rowspan
            var $group_firstTr = $trs.filter('[groupId ="'+groupId+'"]').first();

            $group_firstTr.find('td').each(function(index, ele){
                var td_class = $(ele).attr('class');
                if($.inArray(td_class, sameGroupTd_arr)>-1){
                    var td_rowspan = $(ele).attr('rowspan');
                    if(td_rowspan){
                        $(ele).attr('rowspan',++td_rowspan);
                    }else{
                        $(ele).attr('rowspan', 2);
                    }
                }
            });

            oTr.find('td').each(function(index,ele){
                var td_class = $(ele).attr('class');
                if($.inArray(td_class, sameGroupTd_arr)>-1){
                    $(ele).hide();
                }
            });
        }else {
            if($trs.length == 0){
                groupId = 0;
            }else{
                groupId = i+1;
            }
        }

        oTr.attr('groupId', groupId);
        $("#zhiliaoAdvice_tbody").append(oTr);
    };
    zlsSlectCheckobx();
    //默认全部选中
    $("#zhiliaoAdvice").find('thead [type="checkbox"]').trigger('click')
};
// 新开--治疗方案---常用 双击事件
function zhiliaoChangyhongAdd(bbx01)
{
	var that = this;
	var url = rootUrl + "/clischemedefine/fetchtreatment";
	var params =
	{};
	params.lBBX01A = bbx01;// 治疗方案ID
	params.lACF01 = 1;
	params.lCheck = 1;
	params.lBCK01 = bck01;
	params.BCKyf = 0;
	params.bdp02 = '自费';
	params.abc02 = '普通';
	$.post(url, params, function(data)
	{
		var dataObj = data.list;
		// 双击获取
		for (var i = 0; i < dataObj.length; i++)
		{
			// dataObj[i]['bbx01'] = bbx01;
			addzhiliaoAdvice(dataObj[i]);
		}
	});
}
// 治疗方案：选择医嘱窗口获取选中的医嘱项
function getCheckedAdvice()
{
	var arr = $("#zhiliaoAdvice tbody td:nth-of-type(1) input:checked");
	var idArr =
	[];
	arr.each(function(index, ele)
	{

		var dataStr = $(ele).attr("data-info");
		var dataObj = JSON.parse(dataStr);
		addzhiliaoAdvice(dataObj);

	});

}
// 治疗添加数据
function addzhiliaoAdvice(dataObj)
{
	var bda01 = dataObj.bda01;
	if (bda01 == "1" || bda01 == "2")
	{
		$('#new_order_list a[href="#Xiyao"]').tab('show');
		topTab = "Xiyao";
		var data = $.extend(dataObj,
		{
			'zyyf' : dataObj.bbx01c
		},
		{
			type : "zhiliaofangan"
		});
		addXiyaoCyxm(data);
	}
	// 中药
	else if (bda01 == "3" || bda01 == "8")
	{
		$('#new_order_list a[href="#Zhongyao"]').tab('show');
		topTab = "Zhongyao";
		var url = rootUrl + "/clischemedefine/getVaf1Bybbx01a_8";
		var params =
		{};
		params.bbx01a = dataObj.bbx01a;
		$.ajax({url:url, data:params, type:"get",dataType:"json", success:function(data)
		{
			var list = data.list;
			for (var i = 0; i < list.length; i++)
			{
				if (list[i].bda01 == '3')
				{
					var data = $.extend(list[i],
					{
						'zyyf' : dataObj.bbx01c
					},
					{
						type : "zhiliaofangan"
					},
					{
						bbx01 : list[i].bbx01c
					});
					addZhongyaoCyxm(data);
				}
			}

		}});
	}
	else if (bda01 == "E")
	{
		$('#new_order_list a[href="#Jiancha"]').tab('show');
		topTab = "Jiancha";
		var data = $.extend(dataObj,
		{
			'zyyf' : dataObj.bbx01c
		},
		{
			type : "zhiliaofangan"
		});
		addJianchaCyxm(data);
	}
	else if (bda01 == "L")
	{
		$('#new_order_list a[href="#Jianyan"]').tab('show');
		topTab = "Jianyan";
		var data = $.extend(dataObj,
		{
			'zyyf' : dataObj.bbx01c
		},
		{
			type : "zhiliaofangan"
		});
		addJianyanCyxm(data);
	}
	else if (bda01 == "S")
	{
		$('#new_order_list a[href="#Shoushu"]').tab('show');
		topTab = "Shoushu";
		var url = rootUrl + "/clischemedefine/getVaf1Bybbx01a_s";
		var params =
		{};
		params.bbx01a = dataObj.bbx01a;
		$.ajax({url:url, data:params,type:"get",dataType:"json",async:false,success: function(data)
		{
			var list = data.list;
			if (list.length)
			{
				for (var i = 0; i < list.length; i++)
				{
//					if (list[i].bda01 == '3')
//					{
						var data = $.extend(dataObj, list[i],
						{
							'zyyf' : dataObj.bbx01c
						},
						{
							type : "zhiliaofangan"
						});
						addShoushuCyxm(data);
//					}
				}
			}
			else
			{
				dataObj = $.extend(dataObj,
				{
					type : "zhiliaofangan"
				});
				addShoushuCyxm(dataObj);
			}
		}});
	}
	else
	{
		$('#new_order_list a[href="#Zhiliao"]').tab('show');
		topTab = "Zhiliao";
		var data = $.extend(dataObj,
		{
			'zyyf' : dataObj.bbx01c
		},
		{
			type : "zhiliaofangan"
		});
		addZhiliaoCyxm(data)
	}
	layer.closeAll();// 关闭弹出层
}
// 右侧常用诊断双击事件
/*
 * function xiaDaZhenDuan(vao15,vao01){ if(topTab=="Xiyao") {
 * xyAddchangyongzhenduan(vao15,vao01) } else if(topTab=="Zhongyao") {
 * zyAddchangyongzhenduan(vao15,vao01) } else if(topTab=="Jiancha") {
 * jcAddchangyongzhenduan(vao15,vao01) }else if(topTab=="Jianyan") {
 * jyAddchangyongzhenduan(vao15,vao01) }else if(topTab=="Shoushu") {
 * ssAddchangyongzhenduan(vao15,vao01) } }
 */
// 重新分配组号
function assinGroupNo(table_id)
{
	var $trs = $('#' + table_id).find('tbody>tr');
	if ($trs.length)
	{
		$.each($trs, function(i, o)
		{
			$(o).find('td:eq(1)').text(i + 1);
		});
	}
}
// 另存为方案
function lingcunweifanganEvent()
{
	var bef1 = [];
	GetBef1(bef1);//西药
	GetBef3(bef1);//中药
	GetBefL(bef1);//检验
	GetBefE(bef1);//检查
	GetBefS(bef1);//手术
	GetBefT(bef1);//治疗
	///////////////////////////////////////////////////////华丽的分割线
	if(bef1.length==0)
	{
		layer.msg('没有需要保存的方案，请检查！', {
			time : 2000,
			icon : 0,
			skin: 'layui-layer-msg0'
				
		});
	}
	else
	{
		var that = this;
		var url = rootUrl + "/clischemedefine/catalog";
		$.get(url,
		{}, function(data)
		{
			that.laytplUrl(myurl + "/module/lingcunweifangan.html", data, function(data, html)
			{
				var index = layer.open(
				{
				type : 1,
				// scrollbar : false,
				title : "另存为方案",
				area : [ "700px", "400px"],
				shade : 0.1,
				// maxmin : true,
				content : html,
				closeBtn : 1,
				success : function()
				{
					$("select").select2({
						language: "zh-CN"
					});
					$("#remove_action_cwfz").on("click", function()
					{
						layer.close(index);
					})
				}
				})

			});
		});
	}
}

// 新开更多页面加载

function addMoreType()
{
	var data =
	[
	{
	"name" : "检查",
	"value" : "jc"
	},
	{
	"name" : "检验",
	"value" : "jy"
	},
	{
	"name" : "中药处方",
	"value" : "zy"
	},
	{
	"name" : "西药处方",
	"value" : "xy"
	},
	{
	"name" : "急诊",
	"value" : "jz"
	},
	{
	"name" : "儿童",
	"value" : "et"
	},
	{
	"name" : "毒麻",
	"value" : "dm"
	},
	{
	"name" : "精一",
	"value" : "jyi"
	},
	{
	"name" : "精二",
	"value" : "jer"
	},
	{
	"name" : "手术",
	"value" : "ss"
	},
	{
	"name" : "治疗",
	"value" : "zl"
	},
	{
	"name" : "卫生材料",
	"value" : "wscl"
	}]

	for (var i = 0; i < data.length; i++)
	{
		var html = "<li><label class='checkbox-inline'> <input type='checkbox' id='' value='' >";
		html += data[i].name;
		html += "</label></li>";
		$("#yizhu_more").append(html);
	}

}

// 医师参考
function yishicankEvent()
{
	var that = this;
	var data =
	{};
	that.laytplUrl(myurl + "/module/xk_yishicankao.html", data, function(data, html)
	{
		var index = layer.open(
		{
		type : 1,
		// scrollbar : false,
		title : "医师参考",
		area :
		["80%", "80%"],
		shade : 0.1,
		// maxmin : true,
		content : html,
		closeBtn : 1,
		success : function(index)
		{
		}
		})

	});
}

/* 选择框样式 */
/*function icheck()
{
	$('input').iCheck(
	{
	checkboxClass : 'icheckbox_square-green',
	radioClass : 'iradio_square-green',
	increaseArea : '20%' // optional
	});
}*/
// 关闭layer
//function cancelAdvice()
//{
//	parent.layer.close(parent.layer.getFrameIndex(window.name));// 关闭弹出层
//}

// checkbox全选事件
function choseAllEvent(all, sub)
{
	// var all=$("#advice_table table thead").find("input[type='checkbox']");
	// var sub=$("#advice_table table
	// tbody").find(".innerHead").find("input[type='checkbox']");
	$(all).on("click", function()
	{
		if ($(all).is(':checked'))
		{
			$(sub).prop("checked", true);
		}
		else
		{
			$(sub).removeAttr("checked");
		}
	})
	$(sub).on("click", function()
	{
		var flag = true;
		$(sub).each(function(i, e)
		{
			if (!($(e).is(':checked')))
			{
				flag = false;
			}
		})
		if (flag)
		{
			$(all).prop("checked", true);
		}
		else
		{
			$(all).removeAttr("checked");
		}
	})
}

/* 表单验证 */
/*
 * function formValid(){ $(".valid").Validform({ btnSubmit: "#saveAdvice_btn",
 * tiptype:function(msg,o,cssctl){ //msg：提示信息; //o:{obj:*,type:*,curform:*},
 * obj指向的是当前验证的表单元素（或表单对象），type指示提示的状态，值为1、2、3、4，
 * 1：正在检测/提交数据，2：通过验证，3：验证失败，4：提示ignore状态, curform为当前form对象;
 * //cssctl:内置的提示信息样式控制函数，该函数需传入两个参数：显示提示信息的对象 和 当前提示的状态（既形参o中的type）;
 * 
 * if(!o.obj.is("form")){//验证表单元素时o.obj为该表单元素，全部验证通过提交表单时o.obj为该表单对象; var
 * objtip=o.obj.next().find(".Validform_checktip"); cssctl(objtip,o.type);
 * objtip.text(msg);
 * 
 * var infoObj=o.obj.next(".info"); if(o.type==2){ infoObj.fadeOut(200); }else{
 * if(infoObj.is(":visible")){return;} infoObj.css({ left:120, top:-45
 * }).show().animate({ top:top-35 },200); }
 *  } }, beforeSubmit: function (curform) { debugger; isSave = true; return
 * false; }
 *  })
 *  }
 */

/**
 * 医嘱编辑
 */
function setEditPara()
{
	var dataStr = $("#dataStr").val();
	$('#new_order_list a[href="#NewAdvice"]').tab('show');
	// 新开诊断编辑执行
	var dataStr = $("#dataStr").val();
	var dataObj = dataStr ? JSON.parse(dataStr) : '';
	if (dataObj)// 编辑
	{ 
		var cbm01 = dataObj[0].cbm01;
		editZhenDuanEvent(cbm01);
	}
	//加载常用项目
	typeClick('1');
	//初始化
	init();
	$("#cbm01").val(cbm01);
	$("#dataStr").val(dataStr);
}

function closeChangeTdDiv_zhenduan(){
	$("#neworder_zhenduan").hide();
}
